/**
 * Created by zhouli on 18/3/13
 * Email li.zhou@huilianyi.com
 */
// 成本中心详情
import React from 'react';
import { connect } from 'react-redux';
import { Table, Button, Input, message, Icon, Tooltip, Tabs, Badge, Alert } from 'antd';
import VlService from 'containers/setting/value-list/value-list.service';
import CCService from 'containers/setting/cost-center/cost-center.service';
import menuRoute from 'routes/menuRoute';
import BasicInfo from 'components/basic-info';
import 'styles/setting/cost-center/cost-center-item/cost-center-item-detail.scss';
import { messages, fitText, deepCopy } from 'share/common';
import { SelectDepOrPerson } from 'components/index';
import ListSelector from 'components/list-selector';
import ResizeTable from 'components/resize-table';
import moment from 'moment';

const TabPane = Tabs.TabPane;

class CostCenterItemDetail extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      loading: true,
      confirmLoading: false,
      nowStatus: 'PERSONADD', // 当前的tab
      data: [],
      dataCompany: [],
      dataDep: [], // 管联的部门数据
      costCenterItemUserName: '', // 输入搜索成本中心项人员名称与工号
      costCenterItemDepName: '', // 输入搜索成本中心项 部门名称与编码
      companySelectorShow: false,
      // tabs标题
      tabs: [
        { key: 'PERSONADD', name: messages('setting.key314'/* 按人员添加*/) }, /* 按人员添加*/
        { key: 'DEPARTMENT', name: messages('setting.key315'/* 按部门添加(含子部门)*/) }, /*按部门添加(含子部门)*/
      ],
      columnsCompany: [
        { title: messages('setting.key45'/* 公司代码*/), dataIndex: 'companyCode' },
        { title: messages('setting.key46'/* 公司名称*/), dataIndex: 'companyName' }
      ],
      loadingCompany: false,
      columns: [
        {
          title: messages('setting.key316'/* 工号*/),
          dataIndex: 'employeeID',
          width: '15%'
        },
        {
          title: messages('setting.key317'/* 姓名*/),
          dataIndex: 'fullName',
          width: '15%'
        },
        {
          title: messages('setting.key318'/* 部门*/),
          dataIndex: 'departmentName',
          width: '25%'
        },
        {
          title: messages('setting.key319'/* 职位*/),
          dataIndex: 'title',
          width: '15%'
        },
      ],
      columnsDep: [
        {
          title: messages('setting.key320'/* 部门编码*/),
          dataIndex: 'departmentCode',
          width: '15%'
        },
        {
          title: messages('setting.key321'/* 部门名称*/),
          dataIndex: 'departmentName',
        },
        {
          title: messages('setting.key322'/* 状态*/),
          dataIndex: 'isEnabled',
          width: '25%',
          render: isEnabled => (
            <Badge
              status={isEnabled ? 'success' : 'error'}
              text={isEnabled ? messages('common.status.enable') : messages('common.status.disable')} />)
        },

      ], // 关联的部门表格
      pagination: {
        total: 0,
        page: 0,
        pageSize: 10,
      },
      paginationCompany: {
        total: 0,
        page: 0,
        pageSize: 10,
      },
      // 基本信息中有扩展字段，这个扩展字段是动态的，需要请求详情完毕之后，才能确认，
      // 这里先确定固定的字段
      infoList: [
        {
          // 名称
          type: 'input',
          label: messages('setting.key323'/* 名称*/),
          id: 'name',
          disabled: true
        },
        {
          type: 'input',
          label: messages('setting.key1517')/* 父级成本中心项*/,
          id: 'parentCostCenterItemName',
          disabled: true
        },
        {
          type: 'input',
          label: messages('setting.key324'/* 编码*/),
          id: 'code',
          disabled: true
        },
        {
          type: 'input',
          label: messages('setting.key286'/* 序号*/),
          id: 'sequenceNumber',
          disabled: true
        },
        {
          type: 'input',
          label: messages('setting.key325'/* 经理*/),
          id: 'managerFullName',
          disabled: true
        },
        {
          type: 'switch',
          label: messages('setting.key326'/* 状态*/),
          id: 'enabled'
        },
        {
          type: 'input',
          label: messages('setting.key327'/* 主要部门*/),
          id: 'primaryDepartmentName',
          disabled: true
        },
        {
          type: 'input',
          label: messages('setting.key328'/* 从属部门*/),
          id: '_secondaryDepartmentNames',
          disabled: true
        },
        {
          type: 'switch',
          label: messages('setting.key329'/* 全员可见*/),
          id: 'public',
          disabled: true
        },
      ],
      infoData: {},
      CostCenterDetail: menuRoute.getRouteItem('cost-center-detail', 'key'), // 成本中心详情
      newCostCenterItem: menuRoute.getRouteItem('new-cost-center-item'),
    };
  }

  componentWillMount() {
    const columns = this.state.columns;
    const columnsDep = this.state.columnsDep;
    const columnsCompany = this.state.columnsCompany;
    if (this.props.tenantMode) {
      const operationCompany = {
        title: messages('common.operation'), // "操作",
        dataIndex: 'id',
        render: (text, record) => (
          <span>
            <a onClick={e => this.removeCompanyFromCostCenterItemAssociation(e, record)}>
              {messages('common.delete')}
            </a>
          </span>
        )
      };
      const operation = {
        title: messages('common.operation'), // "操作",
        dataIndex: 'id',
        render: (text, record) => (
          <span>
            <a onClick={e => this.removeUserFromCostCenterItemAssociation(e, record)}>
              {messages('common.delete')}
            </a>
          </span>
        )
      };
      const operationDep = {
        title: messages('common.operation'), // "操作",
        dataIndex: 'id',
        render: (text, record) => (
          <span>
            <a onClick={e => this.removeDepFromCostCenterItemAssociation(e, record)}>
              {messages('common.delete')}
            </a>
          </span>
        )
      };
      columns.push(operation);
      columnsDep.push(operationDep);
      columnsCompany.push(operationCompany);
    }
  }

  componentDidMount() {
    this.getCostCenterItemDetail();
  }

  getCostCenterItemDetail() {
    CCService.getCostCenterItemDetail(this.props.params.itemId)
      .then((res) => {
        const data = res.data;
        this.setSecondaryDepartmentNames(data);
      });
  }

  showCompanySelector = (flag) => {
    this.setState({ companySelectorShow: flag });
  };
  // 由于需要显示顶部信息，要对主要部门，从属部门，
  // 扩展字段进行处理
  // 2020-07-13
  // 1、工会：增加对工会主席、工会主任、经审委员的显示处理
  // 2、项目：增加对项目经理、项目高级经理的显示处理
  // 3、SAP：增加对DO、OC、OM的显示处理
  setSecondaryDepartmentNames = (data) => {
    const tempInfoList = this.state.infoList;
    const tempNewData = {};
    data.roles.map((role) => {
      tempNewData[Object.keys(role)[0]] = role[Object.keys(role)[0]] ? role[Object.keys(role)[0]].fullName : null;
    });
    // if (['MCD2001', 'MCD3001'].includes(this.props.location.query.type)) {
    //   data.companys = data.companyNames;
    //   data.companyNamesArr = data.companys.map(item => item.name);
    //   data.companyNames = data.companyNamesArr.join('、');
    // }
    data = Object.assign(data, { ...tempNewData });
    if (this.props.location.query.type === 'MCD1001') { // SAP成本中心，增加展示DO、OC、OM
      const filterArr = ['T', '9']; // 成本中心编码为T开头为临时餐厅，部门编码以9开头为部门，其余为餐厅
      if (data.code && !filterArr.includes(data.code[0])) {
        const newListItem = ['DO', 'OC', 'OM'].sort((a, b) => a.toLowerCase() > b.toLowerCase() ? 1 : -1);
        newListItem.map((item, index) => {
          const tempObj = {
            type: 'input',
            label: messages(`mcd.cost.center.item.${item}` /* DO、OC、OM */),
            id: item,
            disabled: true
          };
          tempInfoList.push(tempObj);
        });
        console.log(2241, data.roles);
        // sap成本中心新加 CGM/RGM
        // label为CGM/RGM
        // 值为CGM或者RGM，两个只有一个有值
        const isCGM = data.roles.some(item => Boolean(item.CGM))
        tempInfoList.push({
          type: 'input',
          label: 'CGM/RGM',
          id: isCGM ? 'CGM' : 'RGM',
          disabled: true
        })
      }
      // 2020-11-20 sap成本中心增加属性和开店日期字段
      const newItemObj = {
        isDepart: {
          label: '属性',
          id: 'isDepart',
          type: 'select',
          disabled: true
        },
        storeOpenDate: {
          label: '开店日期',
          id: 'storeOpenDate',
          type: 'select',
          disabled: true
        }
      }
      const isDepart = {
        1: '部门',
        2: '餐厅',
        3: '临时餐厅'
      }
      for (const key in newItemObj) {
        tempInfoList.push(newItemObj[key]) 
      }
      data.isDepart = data.isDepart ? isDepart[data.isDepart] : '-'
      data.storeOpenDate = data.storeOpenDate ? moment(data.storeOpenDate).format('YYYY-MM-DD') : '-'
    } else if (this.props.location.query.type === 'MCD2001') { // 项目，增加展示项目经理、项目高级经理、公司
      const newListItem = ['projectManager', 'seniorProjectManager'].sort((a, b) => a.toLowerCase() > b.toLowerCase() ? 1 : -1);
      newListItem.map((item, index) => {
        const tempObj = {
          type: 'input',
          label: messages(`mcd.cost.center.item.${item}` /* 从属部门*/),
          id: item === 'projectCompanyNames' ? 'companyNames' : item,
          disabled: true
        };
        tempInfoList.push(tempObj);
      });
    } else if (this.props.location.query.type === 'MCD3001') { // 工会，增加展示工会主席、工会主任、经审委员、公司
      const newListItem = ['unionChairman', 'unionDirector', 'economicCommittee'].sort((a, b) => a.toLowerCase() > b.toLowerCase() ? 1 : -1);
      newListItem.map((item, index) => {
        const tempObj = {
          type: 'input',
          label: messages(`mcd.cost.center.item.${item}` /* 从属部门*/),
          id: item === 'unionCompanyNames' ? 'companyNames' : item,
          disabled: true
        };
        tempInfoList.push(tempObj);
      });
    }

    data._secondaryDepartmentNames = '';
    if (data.secondaryDepartmentIds && data.secondaryDepartmentIds.length > 0) {
      let i = 0;
      for (const id in data.secondaryDepartmentNames) {
        if (i > 0) {
          data._secondaryDepartmentNames += '、';
        }
        i++;
        data._secondaryDepartmentNames += data.secondaryDepartmentNames[id];
      }
    }

    this.setState({ infoData: data, infoList: tempInfoList }, () => {
      this.getCostCenterItemCompany();
      this.getList(this.state.nowStatus);
      // 后端比较坑
      // 这个地方不能直接显示value，与人员信息扩展字段一样，需要去根据value查询message
      // -----------------这个需要后端优化 不需要前端查询，后端直接给出messageKey   start------------------
      if (this.state.infoData.customFormValues && this.state.infoData.customFormValues.length > 0) {
        this.getPersonDetailEnumerationList();
      }
      // -----------------这个需要后端优化 不需要前端查询，后端直接给出messageKey   ------------------
    });
  }
  // 获取扩展字段中的值列表
  getPersonDetailEnumerationList = () => {
    const infoData = this.state.infoData;
    const customFormValues = infoData.customFormValues;
    for (let i = 0; i < customFormValues.length; i++) {
      if (customFormValues[i].messageKey === 'cust_list') {
        const dataSource = JSON.parse(customFormValues[i].dataSource);
        if (dataSource && dataSource.customEnumerationOID) {
          VlService.getValueListInfo(dataSource.customEnumerationOID)
            .then((res) => {
              this.setPersonDetailEnumerationList(res.data, customFormValues[i]);
            })
            .catch((err) => {
            });
        }
      }
    }
  }

  // 设置扩展字段中的值列表
  // 把值列表挂在对应字段上
  setPersonDetailEnumerationList = (customEnumerationList, filed) => {
    const infoData = deepCopy(this.state.infoData);
    const customFormValues = infoData.customFormValues;
    for (let i = 0; i < customFormValues.length; i++) {
      if (customFormValues[i].fieldOID === filed.fieldOID) {
        customFormValues[i].customEnumerationList = customEnumerationList;
        // 每设置一次，都需要更新一下
        // 后端可能返回的是值列表值对应的code（value），不是messageKey，需要找一下
        // 参见bug13014
        this.setState({
          infoData
        });
      }
    }
  }
  // 根据key获取对应的列表
  getList = (key) => {
    if (key === 'PERSONADD') {
      this.getUserList();
    } else if (key === 'DEPARTMENT') {
      this.getDepartmentList();
    }
  };
  // 获取管理的部门列表
  getDepartmentList = () => {
    this.setState({ loading: true });
    const pagination = this.state.pagination;
    const params = {
      page: pagination.page,
      size: pagination.pageSize,
      keyword: this.state.costCenterItemDepName,
    };
    CCService.getCostcenteritemDepartmentList(this.state.infoData.id, params)
      .then((response) => {
        response.data.map((item) => {
          item.key = item.id;
        });
        pagination.total = Number(response.headers['x-total-count']);
        pagination.current = params.page + 1;
        this.setState({
          dataDep: response.data,
          loading: false,
          pagination
        });
      });
  }

  // 获取分配的公司
  getCostCenterItemCompany() {
    this.setState({ loadingCompany: true });
    const paginationCompany = this.state.paginationCompany;
    const params = {
      page: paginationCompany.page,
      size: paginationCompany.pageSize,
    };
    CCService.getCostCenterItemCompany(params, this.state.infoData.id)
      .then((response) => {
        response.data.map((item) => {
          item.key = item.id;
        });
        paginationCompany.total = Number(response.headers['x-total-count']);
        paginationCompany.current = params.page + 1;
        this.setState({
          dataCompany: response.data,
          loadingCompany: false,
          paginationCompany
        });
      });
  }

  // 得到列表数据
  getUserList() {
    this.setState({ loading: true });
    const pagination = this.state.pagination;
    const params = {
      page: pagination.page,
      size: pagination.pageSize,
      keyword: this.state.costCenterItemUserName,
    };
    CCService.getCostCenterItemUsers(params, this.props.params.itemId)
      .then((response) => {
        response.data.map((item) => {
          item.key = item.id;
        });
        pagination.total = Number(response.headers['x-total-count']);
        pagination.current = params.page + 1;
        this.setState({
          data: response.data,
          loading: false,
          pagination
        });
      });
  }

  // -----非编辑状态---start
  // 渲染非编辑状态
  renderNoEditing = () => {
    const infoData = this.state.infoData;
    const values = infoData.customFormValues ? infoData.customFormValues : [];

    const dom = [];
    for (let i = 0; i < values.length; i++) {
      dom.push(this.renderContentByMessageKey(values[i]));
    }
    return (
      <div className="info-item-wrap">
        {dom}
        <div className="clear" />
      </div>
    );
  };
  renderContentByMessageKey = (field) => {
    const messageKey = field.messageKey;
    // 值列表
    switch (messageKey) {
      case 'cust_list': {
        return this.renderFiled_cust_list(field);
        break;
      }
      case 'input': {
        return this.renderFiled_input(field);
        break;
      }
      case 'user_info': {
        return this.renderFiled_user_info(field);
        break;
      }
    }
  }
  /*
  * 与产品梁文杰，后端陈良钦讨论决定
  * 这个属于特殊的扩展字段，回显的时候就显示后端返回的值（工号）
  * 上传的时候还是显示名字
  * */
  renderFiled_user_info = field => (
    <div className="info-item f-left" key={field.fieldOID}>
      <div className="info-item-title">{field.fieldName}</div>
      <div className="info-item-text">
        {this.renderNoEditingText(field.value)}
      </div>
    </div>
  )
  renderFiled_input = (field) => {
    const messageKey = field.messageKey;
    // 后端可能返回的是值列表值对应的code（value），不是messageKey，需要找一下
    // 参见bug13014
    if (messageKey === 'cust_list' &&
      field.customEnumerationList &&
      field.customEnumerationList.values &&
      field.customEnumerationList.values.length &&
      field.customEnumerationList.values.length > 0) {
      const customEnumerationList = field.customEnumerationList.values;
      for (let i = 0; i < customEnumerationList.length; i++) {
        if (field.value === customEnumerationList[i].value) {
          field.value = customEnumerationList[i].messageKey;
        }
      }
    }
    return (
      <div className="info-item f-left" key={field.fieldOID}>
        <div className="info-item-title">{field.fieldName}</div>
        <div className="info-item-text">
          {this.renderNoEditingText(field.value)}
        </div>
      </div>
    );
  }

  // 渲染字段的内容，根据情况进行截取，鼠标浮动有提示
  renderNoEditingText = (text) => {
    const _text = fitText(text, 16);
    if (_text.text) {
      return (
        <Tooltip title={_text.origin}>
          <span>{_text.text}</span>
        </Tooltip>
      );
    }
    return (text);

  }
  // 渲染字段的内容，根据情况进行截取，鼠标浮动有提示
  renderFiled_cust_list = (field) => {
    const messageKey = field.messageKey;
    // 后端可能返回的是值列表值对应的code（value），不是messageKey，需要找一下
    // 参见bug13014
    if (messageKey === 'cust_list' &&
      field.customEnumerationList &&
      field.customEnumerationList.values &&
      field.customEnumerationList.values.length &&
      field.customEnumerationList.values.length > 0) {
      const customEnumerationList = field.customEnumerationList.values;
      for (let i = 0; i < customEnumerationList.length; i++) {
        if (field.value === customEnumerationList[i].value) {
          field.value = customEnumerationList[i].messageKey;
        }
      }
    }
    return (
      <div className="info-item f-left" key={field.fieldOID}>
        <div className="info-item-title">{field.fieldName}</div>
        <div className="info-item-text">
          {this.renderNoEditingText(field.value)}
        </div>
      </div>
    );
  }

  // -----非编辑状态---end
  // 分页点击
  onChangePager = (pagination, filters, sorter) => {
    this.setState({
      pagination: {
        page: pagination.current - 1,
        pageSize: pagination.pageSize
      }
    }, () => {
      this.getList(this.state.nowStatus);
    });
  };

  // 批量添加人员
  costCenterItemAssociateUsersDTO = (res) => {
    if (res.depList.length < 1 && res.personList.length < 1) {
      // 请选择人员
      message.warn(messages('setting.key330'/* 请选择人员*/));
      return;
    }
    const userOIDs = [];
    const depOIDS = res.depList;
    res.personList.map((item) => {
      userOIDs.push(item.userOID);
    });

    const params = {
      userOIDs,
      departmentDTOs: depOIDS,
      costCenterItemOIDs: [this.props.params.itemId],
      selectMode: 'default',
      costCenterOID: this.props.params.id
    };
    CCService.costCenterItemAssociateUsersDTO(params)
      .then((res) => {
        // 操作成功
        message.success(messages('setting.key331'/* 操作成功*/));
        this.getUserList();
        this.getDepartmentList();
      });
  }
  // 删除分配的公司
  removeCompanyFromCostCenterItemAssociation = (e, record) => {
    CCService.delCompanyToCostcenteritem(record.id)
      .then((res) => {
        // 操作成功
        this.getCostCenterItemCompany();
        message.success(messages('setting.key331'/* 操作成功*/));
      });
  }
  // 删除人
  removeUserFromCostCenterItemAssociation = (e, record) => {
    CCService.removeUserFromCostCenterItemAssociation(record.userOID, this.props.params.itemId)
      .then((res) => {
        // 操作成功
        this.getUserList();
        message.success(messages('setting.key331'/* 操作成功*/));
      });
  }

  // 删除部门
  removeDepFromCostCenterItemAssociation = (e, record) => {
    CCService.delDepartmentToCostcenteritem(record.id)
      .then((res) => {
        // 操作成功
        this.getDepartmentList();
        message.success(messages('setting.key331'/* 操作成功*/));
      });
  }


  // 返回成本中心
  backToCostCenterDetail = () => {
    this.context.router.push(this.state.CostCenterDetail.url.replace(':id', this.props.params.id));
  };

  // 搜索成本中心项的人
  emitEmptyForUser = () => {
    this.userNameInput.focus();
    this.setState({ costCenterItemUserName: '' }, () => {
      this.onChangeCostCenterItemUserName();
    });
  }
  // 搜索成本中心项的部门
  emitEmptyForDep = () => {
    this.DepNameInput.focus();
    this.setState({ costCenterItemDepName: '' }, () => {
      this.onChangeCostCenterItemDepName();
    });
  }
  // 搜索成本中心项的人
  onChangeCostCenterItemUserName = (e) => {
    const { pagination } = this.state;
    pagination.page = 0;
    let costCenterItemUserName = '';
    if (e) {
      costCenterItemUserName = e.target.value;
    }
    this.setState({
      costCenterItemUserName,
      loading: true,
      pagination
    }, () => {
      // 搜索
      this.getUserList();
    });
  }

  // 搜索成本中心项的部门
  onChangeCostCenterItemDepName = (e) => {
    let costCenterItemDepName = '';
    if (e) {
      costCenterItemDepName = e.target.value;
    }
    this.setState({
      costCenterItemDepName,
      loading: true
    }, () => {
      // 搜索
      this.getDepartmentList();
    });
  }

  // 渲染部门或者人员选择组件
  renderDepComponents = () => <div>
    <SelectDepOrPerson
      buttonDisabled={!this.props.tenantMode}
      buttonType={'primary'}
      depResList={['id', 'departmentOID', 'departmentCode',
        'parentDepartmentOID', 'parentDepartmentId', 'custDeptNumber']}
      personResList={['id', 'userOID']}
      title={messages('setting.key332'/* 批量添加*/)}
      onConfirm={this.costCenterItemAssociateUsersDTO} />
  </div>

  // 渲染Tabs
  renderTabs = () => {
    const {
      columns, columnsDep, dataDep, data, loading, pagination, tabs, costCenterItemUserName, costCenterItemDepName,
    } = this.state;
    const suffix = costCenterItemUserName ? (<Icon
      type="close-circle"
      onClick={this.emitEmptyForUser} />) : null;
    const suffixDep = costCenterItemDepName ? (<Icon
      type="close-circle"
      onClick={this.emitEmptyForDep} />) : null;
    return (
      tabs.map((tab) => {
        if (tab.key === 'PERSONADD') {
          return (<TabPane tab={tab.name} key={tab.key}>
            <div>
              <div className="table-header">
                <div className="table-header-buttons">
                  <div className="f-left total-title">
                    {messages('common.total', { total: pagination.total })}
                  </div>
                  {/* 共total条数据 */}
                  <div className="table-header-inp f-right">
                    <Input
                      className="cost-center-item-user-name-search"
                      key={'costCenterItemUserName-search'}
                      placeholder={messages('setting.key333'/* 输入姓名或工号*/)}
                      prefix={<Icon type="search" className="font-disabled" />}
                      suffix={suffix}
                      value={costCenterItemUserName}
                      onChange={this.onChangeCostCenterItemUserName}
                      ref={node => this.userNameInput = node}
                    />
                  </div>
                  <div className="clear" />

                </div>
              </div>
              <ResizeTable
                columns={columns}
                dataSource={data}
                pagination={pagination}
                loading={loading}
                onChange={this.onChangePager}
                rowKey="id"
                bordered
                size="middle"
              />
            </div>

          </TabPane>);
        } else if (tab.key === 'DEPARTMENT') {
          return (<TabPane tab={tab.name} key={tab.key}>
            <div>
              <div className="table-header">
                <div className="table-header-buttons">
                  <div className="f-left total-title">
                    {messages('common.total', { total: pagination.total })}
                  </div>
                  {/* 共total条数据 */}
                  <div className="table-header-inp f-right">
                    <Input
                      className="cost-center-item-user-name-search"
                      key={'costCenterItemDepName-search'}
                      placeholder={messages('setting.key334'/* 输入部门名称/编码*/)}
                      prefix={<Icon type="search" className="font-disabled" />}
                      suffix={suffixDep}
                      value={costCenterItemDepName}
                      onChange={this.onChangeCostCenterItemDepName}
                      ref={node => this.DepNameInput = node}
                    />
                  </div>
                  <div className="clear" />

                </div>
              </div>
              <ResizeTable
                columns={columnsDep}
                dataSource={dataDep}
                pagination={pagination}
                loading={loading}
                onChange={this.onChangePager}
                rowKey="id"
                bordered
                size="middle"
              />
            </div>
          </TabPane>);
        }

      })
    );
  }
  // 点击
  onChangeTabs = (key) => {
    const pagination = this.state.pagination;
    pagination.page = 0;
    pagination.total = 0;
    this.setState({
      nowStatus: key,
      loading: true,
      pagination,
    }, () => {
      this.getList(key);
    });
  };
  // 分配公司
  handleListOk = (result) => {
    this.setState({
      confirmLoading: true
    });
    const companyList = [];
    result.result.map((item) => {
      companyList.push(item.id);
    });
    const params = {
      costCenterItemId: this.state.infoData.id,
      companyIds: companyList
    };

    CCService.linkCostItemToCompany(params)
      .then((res) => {
        this.setState({
          confirmLoading: false
        });
        this.showCompanySelector(false);
        this.getCostCenterItemCompany();
      });
  };

  render() {
    const {
      infoList, infoData, companySelectorShow, loadingCompany, columnsCompany,
      dataCompany, paginationCompany, confirmLoading
    } = this.state;
    return (
      <div className="cost-center-item-detail">

        <Tabs onChange={this.onTabChange}>
          <TabPane tab={messages('setting.key1637')/* 成本中心项详情*/} key="detail">
            <br />
            <BasicInfo
              infoList={infoList}
              infoData={infoData}
              isHideEditBtn
            />
            <div className="cost-center-extend">
              <div className="cost-center-extend-title">
                {messages('setting.key335'/* 扩展字段*/)}
              </div>
              {this.renderNoEditing()}
            </div>
            <p />
            {infoData.public ? <div /> : this.renderDepComponents()}
            {infoData.public ? <div /> : <Tabs onChange={this.onChangeTabs} style={{ marginTop: 20 }}>
              {this.renderTabs()}
            </Tabs>}
          </TabPane>
          <TabPane tab={messages('setting.key730')/* 适用公司*/} key="company">
            <br />
            <Alert
              showIcon
              message={messages('setting.key1638')/* 员工在报销时，只能选择到报销公司适用的成本中心项*/}
              type="info" />
            {infoData.allTenant && <div className="company-des">{messages('setting.key1639')/* 当前账套下启用的全部公司*/}</div>}
            {!infoData.allTenant && <div>
              <div className="table-header">
                <div className="table-header-buttons">
                  <Button type="primary" onClick={() => this.showCompanySelector(true)}>
                    {messages('setting.key62'/* 分配公司*/)}
                  </Button>
                </div>
              </div>
              <ResizeTable
                rowKey="id"
                loading={loadingCompany}
                columns={columnsCompany}
                dataSource={dataCompany}
                pagination={paginationCompany}
                bordered
                size="middle"
              />
              <ListSelector
                visible={companySelectorShow}
                confirmLoading={confirmLoading}
                type="auto_audit_add_company_no_legal"
                extraParams={{
                  setOfBooksId: infoData.setOfBooksId,
                  costCenterItemId: infoData.id,
                  roleType: 'TENANT'
                }}
                onOk={this.handleListOk}
                onCancel={() => this.showCompanySelector(false)} />
            </div>}
          </TabPane>
        </Tabs>
        <a className="back" onClick={this.backToCostCenterDetail}>
          <Icon type="rollback" style={{ marginRight: '5px' }} />
          {messages('common.back')}
        </a>
      </div>
    );
  }

}

CostCenterItemDetail.contextTypes = {
  router: React.PropTypes.object
};

function mapStateToProps(state) {
  return {
    profile: state.login.profile,
    user: state.login.user,
    company: state.login.company,
    tenantMode: state.main.tenantMode,
  };
}

export default connect(mapStateToProps)(CostCenterItemDetail);
